"""连接数据库，创建和删除数据库、表结构"""

import asyncio
import aiomysql

from decouple import config
from config import DB_HOST, DB_PORT, DB_NAME


async def _connect():
    return await aiomysql.connect(
        host=DB_HOST,
        port=DB_PORT,
        user=config('DB_USER', default='root'),
        password=config('DB_PASSWORD', default='root'),
    )


async def init():
    db = await _connect()
    try:
        async with db.cursor() as cursor:
            await cursor.execute(f'''
CREATE database IF NOT EXISTS tornado_auth DEFAULT charset utf8mb4;

use {DB_NAME};

CREATE TABLE user (
    id INT PRIMARY KEY auto_increment,
    username VARCHAR(32) UNIQUE NOT NULL,
    email VARCHAR(32) UNIQUE NOT NULL,
    password VARCHAR(128) UNIQUE NOT NULL,
    date_joined datetime DEFAULT NOW(),
    last_login datetime NULL,
    is_active tinyint(1) DEFAULT 0
) engine=InnoDB DEFAULT charset utf8mb4;
            ''')
    finally:
        db.close()


async def drop():
    db = await _connect()
    try:
        async with db.cursor() as cursor:
            await cursor.execute('DROP database if EXISTS tornado_auth')
    finally:
        db.close()


def main():
    asyncio.run(init())
    # asyncio.run(drop())


if __name__ == '__main__':
    main()
